<template>
  <div>
    <div class="clearflex">
      <el-button class="fl-right" size="small" type="primary" @click="relation">确 定</el-button>
    </div>
    <el-tree
      ref="menuTree"
      :data="menuTreeData"
      :default-checked-keys="menuTreeIds"
      :props="menuDefaultProps"
      default-expand-all
      highlight-current
      node-key="menuId"
      show-checkbox
      @check="nodeChange"
    >
      <template #default="{ node , data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              type="text"
              size="small"
              :style="{color:row.defaultRouter === data.path?'#E6A23C':'#85ce61'}"
              :disabled="!node.checked"
              @click="() => setDefault(data)"
            >
              {{ row.defaultRouter === data.path?"首页":"设为首页" }}
            </el-button>
          </span>
        </span>
      </template>
    </el-tree>

  </div>
</template>

<script setup>
import { getRoleMenuList, saveRoleDefaultMenu, saveRoleMenuList } from '@/api/role'
import { nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'

//接收父组件传来的值
const props = defineProps({
  row: {
    default: function() {
      return {}
    },
    type: Object
  }
})
//定义一个变量来接收父组件传来的方法
const emit = defineEmits(['changeRow'])

const menuTreeData = ref([])
const menuTreeIds = ref([])
const needConfirm = ref(false)
const menuDefaultProps = ref({
  children: 'children',
  label: 'name'
})

const init = async() => {
  {
	  const res = await getRoleMenuList({roleId: props.row.id})
	  if (res.code === 0) {
		  menuTreeData.value = res.data.list
		  menuTreeIds.value = res.data.ids
	  }
  }
}

init()

const setDefault = async(data) => {
	if(props.row.defaultRouter === data.path){
		return
	}
	if(needConfirm.value){
		ElMessage({
		  type: 'warning',
		  message: '请先保存设置'
		})
		return
	}
  const res = await saveRoleDefaultMenu({ roleId: props.row.id, menuId: data.menuId })
  if (res.code === 0) {
    ElMessage({ type: 'success', message: '设置成功' })
    // 调用父组件的changeRow方法，设置行的defaultRouter的值。
    emit('changeRow', 'defaultRouter', data.path)
  }
}
const nodeChange = () => {
  needConfirm.value = true
}
// 暴露给外层使用的切换拦截统一方法
const enterAndNext = () => {
  relation()
}
// 关联树 确认方法
const menuTree = ref(null)
const relation = async() => {
  const checkArr = menuTree.value.getCheckedKeys(false)
  const res = await saveRoleMenuList({
    ids: checkArr,
    id: props.row.id
  })
  if (res.code === 0) {
	needConfirm.value = false
    ElMessage({
      type: 'success',
      message: '菜单设置成功!'
    })
  }
}

defineExpose({ enterAndNext, needConfirm })
</script>

<script>

export default {
  name: 'Menus'
}
</script>

<style lang="scss" scope>
.custom-tree-node{
  span+span{
    margin-left: 12px;
  }
}
</style>
